package at.fhooe.SRWCProject;

import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import at.fhooe.SRWCProject.Bluetooth.ChatActivity;
import at.fhooe.SRWCProject.Bluetooth.Socket.AcceptThread;
import at.fhooe.SRWCProject.Bluetooth.Socket.ConnectionThread;
import at.fhooe.SRWCProject.WiFiDirect.ShareFileActivity;

import java.util.UUID;

public class MainActivity extends Activity implements CreateNdefMessageCallback {

	public static final UUID MY_UUID = UUID.fromString("f895eaf0-867f-11e3-baa7-0800200c9a68");
	public static final String EXTRA_MESSAGE = "123";
	public static final int MESSAGE_TO_SEND = 123;
	public static final int SOCKET_CONNECTED = 1;
	public static final int DATA_RECEIVED = 2;
	public static final int REQUEST_ENABLE_BT = 3;
	public static final int REQUEST_LIST_DEVICE = 4;
	public static final int PORT = 6666;

	private BluetoothAdapter mBluetoothAdapter = null;
	private static ConnectionThread mBluetoothConnection;

	private NfcAdapter mNfcAdapter;
	private PendingIntent mNfcPendingIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (mNfcAdapter == null) {
			Toast.makeText(this, "nfc is not available", Toast.LENGTH_SHORT).show();
			finish();
		} else if (!mNfcAdapter.isEnabled()) {
			Toast.makeText(this, "Please switch on NFC", Toast.LENGTH_SHORT).show();
			startActivity(new Intent(android.provider.Settings.ACTION_NFC_SETTINGS));
		}

		mNfcPendingIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		mNfcAdapter.setNdefPushMessageCallback(this, this);
		initializaBlueToothAccept();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.file_explore, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			Intent toShareActivity = new Intent(this, ShareFileActivity.class);
			startActivity(toShareActivity);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
		IntentFilter[] tagFilters = new IntentFilter[] { tagDetected };

		mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, tagFilters, null);

		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
			onNewIntent(getIntent());
	}

	@Override
	public void onPause() {
		super.onPause();
		mNfcAdapter.disableForegroundDispatch(this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		String address = "";

		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
			intent = getIntent();

		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())
				|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
			Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			if (messages != null) {
				for (int i = 0; i < messages.length; i++) {
					NdefMessage msg = (NdefMessage) messages[i];
					for (NdefRecord record : msg.getRecords()) {
						address = new String(record.getPayload());
					}
				}
			} else {
				Toast.makeText(this, "found empty tag", Toast.LENGTH_SHORT).show();
			}
		}

		if (address != null && !address.isEmpty())
			new at.fhooe.SRWCProject.Bluetooth.Socket.ConnectThread(address, mHandler, MY_UUID).start();
	}

	@Override
	public NdefMessage createNdefMessage(NfcEvent event) {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		String address = mBluetoothAdapter.getAddress();
		NdefMessage msg = new NdefMessage(new NdefRecord[] { NdefRecord.createMime(
				"application/vdn.at.fhooe.SRWCProject", address.getBytes()) });
		return msg;
	}

	public void initializaBlueToothAccept() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		int btState = mBluetoothAdapter.getState();
		if (btState == BluetoothAdapter.STATE_OFF) {
			Toast.makeText(this, "Bluetooth is off", Toast.LENGTH_LONG);
			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, MainActivity.REQUEST_ENABLE_BT);
			}
		} else if (btState == BluetoothAdapter.STATE_ON) {
			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600);
			startActivity(discoverableIntent);
			new AcceptThread(mBluetoothAdapter, mHandler, MainActivity.MY_UUID).start();
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message message) {
			switch (message.what) {
			case SOCKET_CONNECTED: {
				mBluetoothConnection = (ConnectionThread) message.obj;
				BluetoothDevice device = mBluetoothConnection.mmBluetoothSocket.getRemoteDevice();
				String status = mBluetoothConnection.mmBluetoothSocket.getRemoteDevice().getName() + ": online.";
				// mBluetoothConnection.write(status.getBytes());
				Intent i = new Intent(MainActivity.this, ChatActivity.class);
				i.putExtra(EXTRA_MESSAGE, status);
				startActivity(i);
				break;
			}

			case DATA_RECEIVED: {
				String data = (String) message.obj;
				String msg = mBluetoothConnection.mmBluetoothSocket.getRemoteDevice().getName() + ": " + data;
				ChatActivity.mHandler.obtainMessage(ChatActivity.MESSAGE_TO_SEND, msg).sendToTarget();
				break;
			}
			}
			return true;
		}
	});

	public static void sendMessage(String msg) {
		mBluetoothConnection.write(msg.getBytes());
	}

}
